﻿using System.Windows;
using Microsoft.Win32;

namespace Oxage.Services
{
	public class DocumentService
	{
		public static bool NewFile()
		{
			var document = App.ViewModel.Document;
			if (document == null)
			{
				return false;
			}

			if (document.HasChanged)
			{
				var result = MessageBox.Show("Content has changed. Save changes?", "Document", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
				switch (result)
				{
					case MessageBoxResult.Yes:
						if (!SaveFile(true))
						{
							return false;
						}
						break;

					case MessageBoxResult.No:
						break;

					case MessageBoxResult.Cancel:
						return false;
				}
			}

			document.New();
			return true;
		}

		public static bool OpenFile()
		{
			var document = App.ViewModel.Document;
			if (document == null)
			{
				return false;
			}

			if (document.HasChanged)
			{
				var result = MessageBox.Show("Content has changed. Save changes?", "Document", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
				switch (result)
				{
					case MessageBoxResult.Yes:
						if (!SaveFile(true))
						{
							return false;
						}
						break;

					case MessageBoxResult.No:
						break;

					case MessageBoxResult.Cancel:
						return false;
				}
			}

			var dialog = new OpenFileDialog();
			dialog.Filter = "G code (*.cnc)|*.*";

			if (dialog.ShowDialog() == true)
			{
				document.Open(dialog.FileName);
				return true;
			}

			return false;
		}

		public static bool SaveFile(bool forceDialog)
		{
			var document = App.ViewModel.Document;
			if (document == null)
			{
				return false;
			}

			if (!forceDialog && document.CanSaveWithoutDialog)
			{
				document.Save(document.LastUsedFileName);
				return true;
			}

			var dialog = new SaveFileDialog();
			dialog.Filter = "G code (*.cnc)|*.*";

			if (dialog.ShowDialog() == true)
			{
				document.Save(dialog.FileName);
				return true;
			}

			return false;
		}
	}
}
